﻿using Shake.Framework.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Shake.Framework.Utility;
using Shake.Framework.Context;
using fastJSON;

namespace Shake.Framework.View
{
    public static class ShakeResult
    {
        public static ViewResult Shake(this ControllerBase controller, object model = null)
        {
            if (controller == null) return null;

            var view = new ViewResult();
            view.ViewData = new ViewDataDictionary(controller.ViewData)
            {
                Model = model
            };
            view.TempData = controller.TempData;

            GetMaster(controller, view);
            return view;
        }

        private static void GetMaster(ControllerBase controller, ViewResult view)
        {
            var themeAttributes = controller.GetType().GetCustomAttributes(typeof(ThemeAttribute), false) as ThemeAttribute[];
            if (themeAttributes == null || themeAttributes.Length == 0) return;

            var themeName = themeAttributes[0].ThemeName;
            view.MasterName = string.Format("~/Views/Shared/_{0}.cshtml", themeName);
        }

        public static ActionResult PostResult(this ControllerBase controller, PostResult postResult)
        {
            if (controller == null) return null;
            return ToJson(postResult);
        }

        public static bool IsPostRequest(this ControllerBase controller)
        {
            return controller.ControllerContext.RequestContext.HttpContext.Request.HttpMethod.Equals("post", StringComparison.OrdinalIgnoreCase);
        }

        public static ActionResult ToJson<T>(this ControllerBase controller, T result)
        {
            if (controller == null) return null;
            return ToJson(result);
        }

        public static ActionResult ToJson<T>(T result)
        {
            var content = fastJSON.JSON.ToJSON(result, new JSONParameters
            {
                UseUTCDateTime = false,
                ShowReadOnlyProperties = true
            });

            return new ContentResult
            {
                ContentType = "application/json",
                Content = content,
                ContentEncoding = Encoding.UTF8
            };
        }
    }
}
